package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.Business;
import cn.edu.tju.elm.repository.BusinessRepository;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class BusinessService {

    private final BusinessRepository businessRepository;

    // 构造器注入，不依赖Lombok
    public BusinessService(BusinessRepository businessRepository) {
        this.businessRepository = businessRepository;
    }

    /**
     * 查询所有店铺
     */
    @Transactional(readOnly = true)
    public HttpResult<List<Business>> getAllBusinesses() {
        return HttpResult.success(businessRepository.findAll());
    }

    /**
     * 根据ID查询店铺
     */
    @Transactional(readOnly = true)
    public HttpResult<Business> getBusinessById(Long id) {
        Optional<Business> business = businessRepository.findById(id);
        return business.map(HttpResult::success)
                .orElseGet(() -> HttpResult.failure(ResultCodeEnum.NOT_FOUND));
    }

    /**
     * 根据店主查询店铺
     */
    @Transactional(readOnly = true)
    public HttpResult<List<Business>> getBusinessesByOwner(User owner) {
        return HttpResult.success(businessRepository.findByBusinessOwner(owner));
    }

    /**
     * 按名称关键词搜索店铺
     */
    @Transactional(readOnly = true)
    public HttpResult<List<Business>> searchByBusinessName(String keyword) {
        return HttpResult.success(businessRepository.findByBusinessNameContaining(keyword));
    }

    /**
     * 添加新店铺
     */
    @Transactional
    public HttpResult<Business> addBusiness(Business business) {
        Business saved = businessRepository.save(business);
        return HttpResult.success(saved);
    }

    /**
     * 更新店铺信息（仅更新实体类中存在的字段）
     */
    @Transactional
    public HttpResult<Business> updateBusiness(Long id, Business business) {
        return businessRepository.findById(id)
                .map(existing -> {
                    // 仅更新非空字段（部分更新逻辑）
                    if (business.getBusinessName() != null) {
                        existing.setBusinessName(business.getBusinessName());
                    }
                    if (business.getBusinessAddress() != null) {
                        existing.setBusinessAddress(business.getBusinessAddress());
                    }
                    if (business.getBusinessExplain() != null) {
                        existing.setBusinessExplain(business.getBusinessExplain());
                    }
                    if (business.getBusinessImg() != null) {
                        existing.setBusinessImg(business.getBusinessImg());
                    }
                    if (business.getOrderTypeId() != null) {
                        existing.setOrderTypeId(business.getOrderTypeId());
                    }
                    if (business.getStartPrice() != null) {
                        existing.setStartPrice(business.getStartPrice());
                    }
                    if (business.getDeliveryPrice() != null) {
                        existing.setDeliveryPrice(business.getDeliveryPrice());
                    }
                    if (business.getRemarks() != null) {
                        existing.setRemarks(business.getRemarks());
                    }
                    // 店主信息可由管理员修改，保留原有逻辑
                    if (business.getBusinessOwner() != null) {
                        existing.setBusinessOwner(business.getBusinessOwner());
                    }
                    
                    Business updated = businessRepository.save(existing);
                    return HttpResult.success(updated);
                })
                .orElseGet(() -> HttpResult.failure(ResultCodeEnum.NOT_FOUND));
    }
    
    /**
     * 删除店铺
     */
    @Transactional
    public HttpResult<Void> deleteBusiness(Long id) {
        if (businessRepository.existsById(id)) {
            businessRepository.deleteById(id);
            return HttpResult.success();
        }
        return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
    }
}
